package com.cuanbobox.uart;

import android.util.Log;

import com.friendlyarm.FriendlyThings.HardwareControler;

public class UartSom extends Uart {

    private int devfd = -1;
    public static final int DRVFD_CLOSE = -1;

    public UartSom(Callback callback, String path, int baudrate) {
        super( callback, path, baudrate );
    }

    @Override
    public boolean open() {

        try {
            devfd = HardwareControler.openSerialPort( path, baudrate, 8, 1 );
            if (devfd >= 0) {
                Log.d( TAG, path + " open ok " );
                if (callback != null) {
                    timer.schedule( task, 0, 100 );
                }
                return true;
            } else {
                devfd = DRVFD_CLOSE;
                Log.d( TAG, path + "open error" );
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean close() {

        try {
            Log.d( TAG, path + "close" );
            if (devfd != DRVFD_CLOSE) {
                HardwareControler.close( devfd );
                devfd = DRVFD_CLOSE;
            }
            if (callback != null && timer != null) {
                timer.cancel();
                callback = null;
            }
        } catch (Exception e) {

        }
        return true;
    }

    @Override
    public boolean tx(byte[] data, int offset, int length) {
        int ret = DRVFD_CLOSE;
        if (devfd != DRVFD_CLOSE) {
            byte[] buf = new byte[length];
            System.arraycopy( data, offset, buf, 0, length );
            ret = HardwareControler.write( devfd, buf );
        }
        return (ret == DRVFD_CLOSE) ? false : true;
    }

    public int rx(byte[] data, int size) {
        if (devfd != DRVFD_CLOSE && HardwareControler.select( devfd, 0, 0 ) == 1) {
            int retSize = HardwareControler.read( devfd, data, size );
            if (retSize > 0) {
                Log.d( TAG, "rx: " + retSize );
            }
            return retSize;
        }
        return 0;
    }

    @Override
    public boolean getPortState() {
        // TODO 自动生成的方法存根
        return (devfd != DRVFD_CLOSE);
    }

}
